import type { CateItem, QuestionItem, QuestionCreateItem, CateCreateItem } from '@/types/question'
import http from './http'
import { apiMsgProp } from '@/utils/global'
import type { Pagination } from '@/types/global'
import type { SingleItem } from '@/types/quiz'

const QuestionService = {
    /**
     * @function list 題目-获取列表
     * @param categoryId 分类id
     * @param pagination 分页信息
     * @returns 題目列表
     */
    list: async (pagination: Pagination, categoryId?: number): Promise<{ items: QuestionItem[]; pagination: Pagination }> => {
        let apiStr = `/course/question/list?current_page=${pagination.page}&per_page=${pagination.limit}`
        if (categoryId) apiStr += `&category_id=${categoryId}`
        const res = await http.get(apiStr)
        if (res.data.code !== 200) {
            apiMsgProp(res.data.code, res.data.message)
            return Promise.reject(res.data)
        }
        return res.data.data
    },
    /**
     * @function create 題目-新增
     * @param data 題目信息
     * @returns 新增結果
     */
    create: async (data: QuestionCreateItem): Promise<QuestionItem> => {
        const { answer_feedback, answer, ...rest } = data
        const _data: any = rest
        _data.answer_feedback = JSON.stringify(answer_feedback)
        _data.answer = JSON.stringify(answer)

        const res = await http.post('/course/question/add', _data)
        apiMsgProp(res.data.code, res.data.message)
        if (res.data.code !== 200) return Promise.reject(res.data)
        return res.data.data.items
    },
    /**
     * @function delete 題目-刪除
     * @param ids 題目id列表
     * @returns 刪除結果
     */
    delete: async (ids: number[]): Promise<void> => {
        const res = await http.delete('/course/question/batch', { data: { ids } })
        apiMsgProp(res.data.code, res.data.message)
        if (res.data.code !== 200) return Promise.reject(res.data)
    },
    /**
     * @function getById 題目-获取单条
     * @param id 題目id
     * @returns 題目信息
     */
    getById: async (id: number): Promise<QuestionItem> => {
        const res = await http.get(`/course/question/${id}/info`)
        if (res.data.code !== 200) {
            apiMsgProp(res.data.code, res.data.message)
            return Promise.reject(res.data)
        }
        return res.data.data.items
    },
    /**
     * @function update 題目-新增
     * @param data 題目信息
     * @returns 新增結果
     */
    update: async (data: QuestionCreateItem): Promise<void> => {
        const { answer_feedback, answer, ...rest } = data
        const _data: any = rest
        _data.answer_feedback = JSON.stringify(answer_feedback)
        _data.answer = JSON.stringify(answer)

        const res = await http.post(`/course/question/${data.id}/update`, _data)
        apiMsgProp(res.data.code, res.data.message)
        if (res.data.code !== 200) return Promise.reject(res.data)
    },
    /**
     * @function cateList 題目-获取分类-全部分类
     * @returns 題目分类列表
     */
    cateList: async (per_page: number = 10000): Promise<{ items: CateItem[]; pagination: Pagination }> => {
        const res = await http.get(`/course/question/cate/list?per_page=${per_page}`)
        if (res.data.code !== 200) {
            apiMsgProp(res.data.code, res.data.message)
            return Promise.reject(res.data)
        }

        res.data.data.items.forEach((item: CateItem) => {
            item.children = []
        })

        // 构建树形结构
        const itemMap = res.data.data.items.reduce((map: Record<number, CateItem>, item: CateItem) => {
            map[item.id] = item
            return map
        }, {})

        const treeData: CateItem[] = []
        res.data.data.items.forEach((item: CateItem) => {
            if (item.parent_id === 0) {
                treeData.push(item)
            } else {
                const parent = itemMap[item.parent_id]
                parent?.children?.push(item)
            }
        })

        return {
            items: treeData,
            pagination: res.data.data.pagination,
        }
    },
    /**
     * @function createCate 題目-新增分类
     * @param data 分类信息
     * @returns 新增分类结果
     */
    createCate: async (data: CateCreateItem): Promise<QuestionCreateItem> => {
        const res = await http.post('/course/question/cate/add', data)
        apiMsgProp(res.data.code, res.data.message)
        if (res.data.code !== 200) return Promise.reject(res.data)
        return res.data.data.items
    },
    /**
     * @function updateCate 題目-更新分类
     * @param data 分类信息
     * @returns 更新分类结果
     */
    updateCate: async (data: CateCreateItem): Promise<void> => {
        const res = await http.post(`/course/question/cate/update/${data.id}`, data)
        apiMsgProp(res.data.code, res.data.message)
        if (res.data.code !== 200) return Promise.reject(res.data)
    },
    /**
     * @function deleteCate 題目-刪除分类
     * @param ids 分类id组
     * @returns 刪除分类结果
     */
    deleteCate: async (ids: number[]): Promise<void> => {
        const res = await http.post(`/course/question/cate/delMultiCate`, { ids })
        apiMsgProp(res.data.code, res.data.message)
        if (res.data.code !== 200) return Promise.reject(res.data)
    },
    /**
     * @function questionByIdAndRecordId 查看单题目详情
     * @param question_id 题目id
     * @param id 作答记录id
     * @returns
     */
    questionByIdAndRecordId: async (id: number, question_id: number): Promise<SingleItem> => {
        const res = await http.get(`/course/quiz/singleDetail?id=${id}&question_id=${question_id}`)
        if (res.data.code !== 200) {
            apiMsgProp(res.data.code, res.data.message)
            return Promise.reject(res.data)
        }
        res.data.data.items.question.answer = JSON.parse(res.data.data.items.question.answer)
        return res.data.data.items
    },
}

export default QuestionService
